package cn.edu.hunau.dao.impl;


import cn.edu.hunau.dao.OrderItemDao;
import cn.edu.hunau.exception.DaoException;
import cn.edu.hunau.pojo.OrderItem;
import cn.edu.hunau.pojo.Product;
import cn.edu.hunau.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 苏佳
 * @Date 2022 11 13 21 41
 **/
public class OrderItemDaoImpl implements OrderItemDao {

    @Override
    public void insert(List<OrderItem> orderItems) throws DaoException {
        String sql = "insert into t_orderitem(oid,pid,pimage,size,pname,price,qty) values(?,?,?,?,?,?,?)";


        // 1. 获得Connection对象
        Connection conn = null;
        // 2.声明PreparedStatement对象
        PreparedStatement pstm = null;
        try {
            //获得手动管理的Connection对象
            conn = DBUtils.beginTransaction();
            pstm = conn.prepareStatement(sql);
            for(OrderItem item:orderItems){
                Product p = item.getProduct();
                pstm.setObject(1,item.getOrder().getId());
                pstm.setObject(2,p.getId());
                pstm.setObject(3,p.getPimage());
                pstm.setObject(4,item.getSize());
                pstm.setObject(5,p.getName());
                pstm.setObject(6,item.getShoppingPrice());
                pstm.setObject(7,item.getQty());
                pstm.addBatch();    //加入缓存区
            }
            // 执行批处理的语句语句
            pstm.executeBatch();
        } catch (Exception e) {
            throw new DaoException(e);
        } finally {
            DBUtils.close(null, pstm);
        }
    }

    @Override
    public List<OrderItem> queryByOid(String oid) throws DaoException {
        String sql="select pid,pimage,size,pname,price,qty from t_orderitem where oid=?";
        return DBUtils.query(sql,rs -> {
            List<OrderItem> datas = new ArrayList<>();
            OrderItem oi=null;
            Product p=null;
            while(rs.next()){
                oi=new OrderItem();
                p=new Product();
                p.setId(rs.getInt("pid"));
                p.setPimage(rs.getString("pimage"));
                p.setName(rs.getString("pname"));
                oi.setProduct(p);
                oi.setQty(rs.getInt("qty"));
                oi.setSize(rs.getInt("size"));
                oi.setShoppingPrice(rs.getDouble("price"));
                datas.add(oi);
            }
            return datas;
        },oid);
    }

    @Override
    public void deleteOrderItemBy(String oid) throws DaoException {
        String sql="delete from t_orderitem where oid=?";
        DBUtils.updateTransaction(sql,oid);
    }
}
